using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Bll;
using Common;
using Web.Extension;
using Microsoft.AspNetCore.Authorization;
using Web.Controllers;
using System.IO;
using System.Data;
using Web.Util;
using Web.Filter;

namespace Web.Admin.Controllers
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [Authorize("admin")]
    [QueryFilter]
    public class ClassScheduleController : MyBaseController<ClassSchedule>
    {
        IClassScheduleBll bll;
        public IClasssBll classsBll { get; set; }
        public IClassroomBll classroomBll { get; set; }
        public ITimeTableBll timeTableBll { get; set; }
        public ITeacherBll teacherBll { get; set; }
        public ICourseBll courseBll { get; set; }
        public ClassScheduleController(IClassScheduleBll bll)
        {
            this.bll = bll;
        }
        // GET: api/List/ClassSchedule
        [HttpGet]
        public Result List([FromQuery] Dictionary<string, string> where)
        {
            //return Result.Success("succeed").SetData(bll.SelectAll(o => true, pageNo, pageSize));
            return Result.Success("succeed").SetData(bll.Query(where));
        }

        // GET: api/ClassSchedule/Get/5
        [HttpGet("{id}")]
        public Result Get([FromQuery] Dictionary<string, string> where)
        {
            return Result.Success("succeed").SetData(bll.SelectOne(where));
        }
        // POST: api/ClassSchedule/Add
        [HttpPost]
        public Result Add(ClassSchedule o)
        {
            return ModelState.IsValid ? (bll.Add(o) ? Result.Success("添加成功") : Result.Error("添加失败")) : Result.Error("添加失败!" + ModelState.GetAllErrMsgStr(";")); ;
        }

        // Post: api/ClassSchedule/Update
        [HttpPost]
        public Result Update(ClassSchedule o)
        {
            return ModelState.IsValid ? (bll.Update(o) ? Result.Success("修改成功").SetData(o) : Result.Error("修改失败")) : Result.Error("修改失败!" + ModelState.GetAllErrMsgStr(";")); ;
        }

        // Get: api/ClassSchedule/Delet/5
        [HttpGet("{id}")]
        public Result Delete([FromQuery] Dictionary<string, string> where)
        {
            return bll.Delete(where) ? Result.Success("删除成功") : Result.Error("删除失败");
        }
        [HttpPost]
        public Result BatchDelete([FromForm] Dictionary<string, string> where)
        {
            return bll.Delete(where) ? Result.Success("删除成功") : Result.Error("删除失败");
        }
        [HttpPost()]
        //public async Task<Result> Import(IFormFile file,[FromBody]int classsId)
        public Result Import([FromForm] IFormCollection formCollection)
        {
            //var classsId = Convert.ToInt32(formCollection["classsId"]);
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
            foreach (IFormFile file in fileCollection)
            {
                var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (string.IsNullOrEmpty(ext) || !ExcelExt.Contains(ext))
                {
                    return Result.Error("上传失败,请选择xlsx类型文件");
                }
                if (file.Length > 0)
                {
                    if (file.Length > ImgSizeLimit)
                    {
                        var size = ImgSizeLimit / 1024;
                        return Result.Error($"上传失败,文件超过大小{size}KB");
                    }
                    string filePath = "/temp/" + file.FileName;
                    DataTable dt = OfficeHelper.ReadExcelToDataTable(file.OpenReadStream(),"教室课表");
                    foreach (DataRow row in dt.Rows)
                    {
                        ClassSchedule s = new ClassSchedule();
                        //教室编号
                        var classroomSn = row["教室编号"].ToString();
                        var classroom = classroomBll.SelectOne(o => o.Sn == classroomSn);
                        if (classroom==null)
                        {
                            return Result.Error($"导入失败,未找到教室编号{classroomSn}相关的记录");
                        }
                        s.ClassroomSn = classroomSn;
                        s.Classroom = classroom;
                        //上课班级
                        var classname = row["上课班级"].ToString();
                        var cls = classsBll.SelectOne(o => o.Name == classname);
                        if (classname == null)
                        {
                            return Result.Error($"导入失败,未找到班级名称{classname}相关的记录");
                        }
                        s.Classs = cls;
                        //上课时段
                        var timeTableSn = row["课时编号"].ToString();
                        var timeTable = timeTableBll.SelectOne(o => o.Sn == timeTableSn);
                        if (timeTable == null)
                        {
                            return Result.Error($"导入失败,未找到课时编号{timeTableSn}的相关记录");
                        }
                        s.TimeTableSn = timeTableSn;
                        s.TimeTable = timeTable;
                        //日期
                        var date = row["日期"].ToString();
                        s.Date = DateTime.Parse(Convert.ToDateTime(date).ToShortDateString());
                        //教师编号
                        var teacherSn = row["教师编号"].ToString();
                        var teacher = teacherBll.SelectOne(o => o.Timetable_Sn == teacherSn);
                        if (teacher == null)
                        {
                            return Result.Error($"导入失败,未找到教师编号{teacherSn}的相关记录");
                        }
                        s.TeacherSn = teacherSn;
                        s.Teacher = teacher;
                        //课程编号
                        var courseSn = row["课程编号"].ToString();
                        var course = courseBll.SelectOne(o => o.Sn == courseSn);
                        if (course == null)
                        {
                            return Result.Error($"导入失败,未找到课程编号{courseSn}的相关记录");
                        }
                        s.CourseSn = courseSn;
                        s.Course = course;
                        //课程内容
                        var content = row["授课内容"].ToString();
                        s.Content= content;

                        this.bll.Add(s);
                    }
                    //using (var stream = System.IO.File.Create(webHostEnvironment.WebRootPath + filePath))
                    //{

                    //    //await file.CopyToAsync(stream);
                    //}
                    return Result.Success("导入成功");
                }
                else
                {
                    return Result.Success("导入失败,空文件");
                }
            }
            return Result.Success("导入失败,请上传文件");
        }
    }
}
